package com.example.shrio;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.admin.entity.CommonUser;
import com.example.admin.service.ICommonUserService;
import com.example.shrio.conf.CustomizedToken;
import com.example.shrio.error.LoginNullUserException;
import com.example.shrio.error.LoginPassWordException;
import com.example.util.encryption.EncryptionUtil;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义认证、权限（普通用户）
 * 
 * @author wangkai
 *
 * @date: 2019年5月31日 下午1:15:15
 */
public class CommonUserShiroRealm extends AuthorizingRealm {

	@Autowired
	private ICommonUserService userService;

	/*
	 * (non-Javadoc) 认证
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.
	 * apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		// 获取用户的输入的账号.
		CustomizedToken customizedToken = (CustomizedToken) token;
		String account = (String) customizedToken.getPrincipal();
		QueryWrapper<CommonUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("account", account);
		CommonUser userInfo = userService.getOne(queryWrapper);
		if (userInfo == null) {
			throw new LoginNullUserException("当前账号未注册");
		}
		String password = new String((char[]) token.getCredentials());
		String newPassword = EncryptionUtil.encryptionMd5(password, userInfo.getSalt(), 2);
		if (!newPassword.equals(userInfo.getPassword())) {
			throw new LoginPassWordException("当前输入密码不正确");
		}
		if (userInfo.getStart().intValue() == 1) { // 账户冻结
			throw new LockedAccountException("账户冻结");
		}
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(userInfo, // 用户
				password, // 密码
				getName() // realm name
		);
		return authenticationInfo;
	}

	/*
	 * (non-Javadoc) 分配权限
	 * 
	 * @see
	 * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
	 * .shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		CommonUser userInfo = (CommonUser) principals.getPrimaryPrincipal();
		
		return authorizationInfo;
	}

}
